<template>
  <el-card shadow="never">
    <xz-form ref="formRef" :items="items" v-model="form" :rules="rules">
      <template #timePicker="scope">
        <el-time-picker
          is-range
          v-model="form[scope.item.prop]"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          placeholder="选择时间范围"
        >
        </el-time-picker>
      </template>
    </xz-form>
    <el-button type="primary" @click="onSubmit">提交</el-button>
  </el-card>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from '@vue/runtime-core'
import { ElForm } from 'element-plus'
import XzForm from '@/components/XzForm/index.vue'

export default defineComponent({
  components: { XzForm },
  setup() {
    const items = [
      {
        type: 'input',
        label: '姓名',
        prop: 'name',
        placeholder: '请输入姓名',
        rules: { required: true, trigger: 'blur' },
        custom: { style: 'width:220px' }
      },
      {
        type: 'select',
        label: '年级',
        prop: 'grade',
        placeholder: '请选择年级',
        rules: { required: true },
        options: [
          { value: 1, label: '一年级' },
          { value: 2, label: '二年级' }
        ]
      },
      {
        type: 'date',
        label: '入校时间',
        prop: 'date',
        placeholder: '请选择入校时间',
        custom: { type: 'daterange' }
      },
      {
        type: 'radio',
        label: '是否及格',
        prop: 'rank',
        options: [
          { value: 1, label: '及格' },
          { value: 0, label: '没及格' }
        ]
      },
      {
        require: true,
        type: 'switch',
        label: '是否公开',
        prop: 'public'
      },
      {
        type: 'checkbox',
        label: '兴趣爱好',
        prop: 'hobby',
        selectLabel: 'key',
        options: [
          { value: 1, key: '篮球' },
          { value: 2, key: '足球' },
          { value: 3, key: '游戏' }
        ]
      },
      {
        type: 'textarea',
        label: '个人评价',
        prop: 'desc'
      },
      {
        type: 'slot',
        slot: 'timePicker',
        label: '活动时间',
        prop: 'timeRang'
      }
    ]

    const rules = {
      date: [{ type: 'array', required: true, message: '请选择日期', trigger: 'change' }],
      hobby: [
        { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
      ]
    }

    const form = reactive({ name: '', rank: [], hobby: [], timeRang: [] })

    const formRef = ref<typeof ElForm>()

    const resetFields = () => {
      formRef.value && formRef.value.resetFields()
    }

    const onSubmit = () => {
      formRef.value &&
        formRef.value.validate().then((valid: boolean) => {
          if (valid) {
            console.log('success')
          }
        })
    }

    return {
      form,
      rules,
      items,
      formRef,
      resetFields,
      onSubmit
    }
  }
})
</script>
